/**
 * @file 蚂蚁修工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */

layui.define(['element', 'layer', 'searchPage', 'laydate', 'laytpl', 'formSelects', 'list_modify_operation', 'zmnUtils'], function(exports) {
    var $ = layui.$;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var zmnUtils = layui.zmnUtils;
    var searchPage = layui.searchPage;

    var ENTRUST_LIST_URL = '/order/entrust/ajax/list.action';
    var ENTRUST_EXPORT_URL = '/order/entrust/export.action';

    var datePickerSelectorArray = [
        'receiveTime',
        'dutyTime',
        'distributeTime',
        'visitTime',
        'payTime',
        'completeTime',
        'checkoutTime',
        'accountTime',
        'accountTime',
        'replyVisitTime',
        'partReimburseTime',
        'refundAmountTime'
    ];

    var multipleSelectNameArray = [
        'cityIdList',
        'channelIdList',
        'workStatus'
    ];

    /**
     * 渲染日期选择器
     * @param selector 日期选择器的选择器或者 Dom 对象
     */
    function renderDatePicker(selector) {
        var config = {
            elem: selector,
            format: selector.indexOf('Start') !== -1 ? 'yyyy-MM-dd' : 'yyyy-MM-dd'
        };
        laydate.render(config);
    }

    /**
     * 初始化页面的所有日期组件
     */
    function initALLDatePickers() {
        $.each(datePickerSelectorArray, function(index, keyword) {
            $.each(['Start', 'End'], function(i, suffix) {
                renderDatePicker('#' + keyword + suffix);
            });
        });
    }

    /**
     * 打开对话框
     * @param {Object} config 配置
     */
    function openDialog(config) {
        var defaultConfig = {
            type: 2,
            content: '/',
            title: '',
            shade: [0.8, '#393D49'],
            area: ['80%', '80vh'],
            minWidth: '960px',
            zIndex: layer.zIndex, // 重点1
            success: function(layero) {
                parent.layer.setTop(layero); // 重点2
            }
        };

        var normalizedConfig = Object.assign({}, defaultConfig, config);

        parent.layer.open(normalizedConfig);
    }

    /**
     * 打开手机单详情页
     * @param entrustId
     */
    function openDetailDialog(entrustId) {
        openDialog({
            title: '详情',
            content: zmnUtils.serializeURL(OMS_BASE_URL + '/order/entrust/detail.action', {
                entrustId: entrustId
            })
        });
    }

    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field) {
        var params = {};

        // 整理时间
        datePickerSelectorArray.forEach(function(keyword) {
            var startSelector = keyword + '.start';
            var endSelector = keyword + '.end';

            var startTime = field[startSelector];
            var endTime = field[endSelector];

            if (startTime || endTime) {
                startTime = startTime ? startTime + ' ' + '00:00:00' : '';
                endTime = endTime ? endTime + ' ' + '23:59:59' : '';

                params[keyword] = startTime + ',' + endTime;

                field[startSelector] = '';
                field[endSelector] = '';
            }
        });

        // 整理客户电话
        if (field['concatPhone'].length === 4) {
            params['concatPhoneEnd4'] = field['concatPhone'];
            field['concatPhone'] = null;
        }

        // 整理工单号
        if (field['code'].length === 6) {
            params['codeEnd6'] = field['code'];
            field['code'] = '';
        }

        // 整理操作类型、操作员
        if (field['operate.operateType'] || field['operate.operatorId']) {
            params['operate'] = {
                operateType: field['operate.operateType'],
                operatorId: field['operate.operatorId']
            };

            field['operate.operateType'] = null;
            field['operate.operatorId'] = null;
        }

        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });

        return params;
    }

    searchPage.init({
        id: 'zmn-work-table',
        searchURL: ENTRUST_LIST_URL,
        exportURL: ENTRUST_EXPORT_URL,
        defaultParams: {},
        orderObj: {
            orderField: 'receiveTime',
            defaultOrder: 2
        },
        tableConfig: {
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'print']
        },
        init: function() {
            initALLDatePickers();
        },
        parseParams: function(dataObj) {
            let pageUrl = window.location.href;
            var params = normalizeSearchParams(dataObj.field)
            var filter_name = ''
            Object.keys(params).forEach((item, index) => {
                var fifname = $('[name^="' + item + '"]').parents('.layui-input-inline').eq($('[name^="' + item + '"]').parents('.layui-input-inline').length - 1).prev().text().split('：')[0]

                if (index != Object.keys(params).length - 1) {
                    filter_name = filter_name + fifname + '|'
                } else {
                    filter_name = filter_name + fifname
                }

            })

            try {
                if (filter_name.substring(filter_name.length - 1) == '|') {
                    filter_name = filter_name.substring(0, filter_name.length - 1)
                }
                console.log(filter_name)
                var data = {
                    employee_name: loginStaff.realName, // 内部员工姓名,
                    employee_id: loginStaff.staffId,
                    department_name: loginStaff.deptName, // 员工部门名称
                    department_id: loginStaff.deptId,
                    menu: path_name, //菜单目录路径名称
                    filter_name: filter_name,
                    tab_name: tabName || ''
                }
                webTrackingUtil('SYS_ADMIN_QUERY', pageUrl, 'click', 'SYS_ADMIN_QUERY_CLICK', data)
            } catch (error) {
                console.log(error)
            }

            return normalizeSearchParams(dataObj.field);
        },
        rowDoubleHandler: function(rowObj) {
            openDetailDialog(rowObj.data.workId);
        },
        toolbarHandler: function(obj) {
            switch (obj.event) {
                case 'addMemberOrder':
                    openDialog({
                        title: '新增手机订单',
                        content: OMS_BASE_URL + '/order/entrust/add',
                        end: function() {}
                    });
                    break;
                default:
                    break;
            }
        },
        toolHandler: function(obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'detail':
                    openDetailDialog(data.workId);
                    break;
                default:
                    break;
            }
        },
    });

    exports('oms_entrust_work_list');
});